<template>
  <div class="app-container">
    <div class="document-layout">
      <!-- 左侧元数据区域 -->
      <div class="metadata-panel">
        <div class="panel-header">
          <h2>文档元数据</h2>
        </div> 
        <el-scrollbar class="metadata-scrollbar">
          <el-form :model="documentData" label-position="top" class="metadata-form" size="small">
            <el-form-item label="档号">{{ documentData.dh || '-' }}</el-form-item>
            <el-form-item label="题名">{{ documentData.tm || '-' }}</el-form-item>
            <el-form-item label="主题词">{{ documentData.ztc || '-' }}</el-form-item>
            <el-form-item label="密级">{{ documentData.mj || '-' }}</el-form-item>
            <el-form-item label="保管期限">{{ documentData.bgqx || '-' }}</el-form-item>
            <el-form-item label="分类号">{{ documentData.flh || '-' }}</el-form-item>
            <el-form-item label="案卷号">{{ documentData.ajh || '-' }}</el-form-item>
            <el-form-item label="件号">{{ documentData.jh || '-' }}</el-form-item>
            <el-form-item label="关键词">{{ documentData.gjc || '-' }}</el-form-item>
            <el-form-item label="类别号">{{ documentData.lbh || '-' }}</el-form-item>
            <el-form-item label="文种">{{ documentData.wz || '-' }}</el-form-item>
            <el-form-item label="时间">{{ documentData.sj || '-' }}</el-form-item>
            <el-form-item label="文件编号">{{ documentData.wjbh || '-' }}</el-form-item>
            <el-form-item label="载体类型">{{ documentData.ztlx || '-' }}</el-form-item>
            <el-form-item label="载体数量">{{ documentData.ztsl || '-' }}</el-form-item>
            <el-form-item label="载体单位">{{ documentData.ztdw || '-' }}</el-form-item>
            <el-form-item label="载体规格">{{ documentData.ztgg || '-' }}</el-form-item>
            <el-form-item label="责任者">{{ documentData.zrz || '-' }}</el-form-item>
            <el-form-item label="微缩号">{{ documentData.wsh || '-' }}</el-form-item>
            <el-form-item label="档案管号">{{ documentData.dagh || '-' }}</el-form-item>
            <el-form-item label="数据类型">{{ documentData.sjlx || '-' }}</el-form-item>
            <el-form-item label="附注">{{ documentData.fz || '-' }}</el-form-item>
          </el-form>
        </el-scrollbar>
      </div>

      <!-- 右侧PDF查看区域 -->
      <div class="pdf-panel">
        <div class="panel-header">
          <div class="left-controls">
            <el-radio-group v-model="pdfViewMode" size="small">
              <el-radio-button label="single">单层PDF</el-radio-button>
              <el-radio-button label="double">双层PDF</el-radio-button>
              <el-radio-button label="text">文本</el-radio-button>
            </el-radio-group>

            <!-- 添加搜索控件 -->
            <div class="search-controls" v-if="pdfViewMode === 'double'">
              <el-input
                v-model="searchText"
                placeholder="搜索文本"
                size="small"
                class="search-input"
                @keyup.enter.native="searchInPdf"
                clearable
                @clear="clearSearch"
              >
                <el-button slot="append" icon="el-icon-search" @click="searchInPdf"></el-button>
              </el-input>
              <el-button 
                size="small" 
                icon="el-icon-arrow-up" 
                :disabled="currentMatchIndex <= 0 || matchCount === 0" 
                @click="navigateMatch('prev')"
                class="nav-button"
                title="上一个匹配项"
              ></el-button>
              <el-button 
                size="small" 
                icon="el-icon-arrow-down" 
                :disabled="currentMatchIndex >= matchCount - 1 || matchCount === 0" 
                @click="navigateMatch('next')"
                class="nav-button"
                title="下一个匹配项"
              ></el-button>
              <span class="match-info" v-if="matchCount > 0">
                {{ currentMatchIndex + 1 }}/{{ matchCount }}
              </span>
              <el-button 
                v-if="matchCount > 0"
                size="small" 
                icon="el-icon-close" 
                @click="clearSearch"
                class="nav-button clear-button"
                title="清除搜索结果"
                type="danger"
                plain
              ></el-button>
            </div>
          </div>
        </div>
        
        <div class="pdf-container" :class="pdfViewMode">
          <!-- 单层PDF查看 -->
          <div v-if="pdfViewMode === 'single'" class="pdf-iframe-container">
            <div v-if="pdfUrl" class="iframe-container">
              <embed
                :src="pdfUrl"
                type="application/pdf"
                class="pdf-embed"
                width="100%"
                height="100%"
                alt="PDF文档"
              />
            </div>
            <div v-else class="pdf-placeholder">
              <div class="empty-placeholder">
                <i class="el-icon-document"></i>
                <p>正在加载PDF文件...</p>
              </div>
            </div>
          </div>

          <!-- 双层PDF查看 -->
          <div v-else-if="pdfViewMode === 'double'" class="pdf-iframe-container">
            <div v-if="pdfUrl" class="iframe-container">
              <!-- 使用vue-pdf-embed组件替换iframe -->
              <div class="pdf-embed-container">
                <vue-pdf-embed
                  ref="pdfEmbed"
                  :source="pdfUrl"
                  :page="currentPage"
                  @rendered="onPdfRendered"
                  @loading="loading = true"
                  @loaded="onPdfLoaded"
                  @error="handlePdfError"
                />
                
                <!-- 添加搜索高亮覆盖层 -->
                <div v-if="searchText && matchCount > 0" class="search-highlights-overlay">
                  <div 
                    v-for="(match, index) in searchMatches" 
                    :key="index"
                    class="search-highlight"
                    :class="{ 'current-match': index === currentMatchIndex }"
                    :style="match.style"
                    @click="navigateToMatch(index)"
                  ></div>
                </div>
              </div>
            </div>
            <div v-if="loading" class="pdf-loading">
              <div class="el-loading-spinner">
                <i class="el-icon-loading"></i>
                <p class="el-loading-text">加载PDF中...</p>
              </div>
            </div>
            <div v-else-if="!pdfUrl" class="pdf-placeholder">
              <div class="empty-placeholder">
                <i class="el-icon-document"></i>
                <p>正在加载PDF文件...</p>
              </div>
            </div>
          </div>

          <!-- 文本查看 -->
          <div v-else-if="pdfViewMode === 'text'" class="text-container">
            <el-scrollbar class="text-scrollbar">
              <div class="document-paper" v-if="!loading">
              
           
                <div class="document-content" v-if="documentData.content">
                  <pre>{{ documentData.content }}</pre>
                </div>
                <div class="empty-content" v-else>
                  <i class="el-icon-document"></i>
                  <p>暂无文档内容</p>
                  <el-button size="small" type="primary" @click="pdfViewMode = 'single'">查看PDF</el-button>
                </div>
              </div>
              <div class="loading-placeholder" v-else>
                <div class="el-loading-spinner">
                  <i class="el-icon-loading"></i>
                  <p class="el-loading-text">正在加载中...</p>
                </div>
              </div>
            </el-scrollbar>
          </div>

          <!-- PDF加载中或错误状态 -->
          <div v-if="loading && !pdfLoadError" class="pdf-overlay loading">
            <el-progress 
              v-if="loadingStatus === 'success'" 
              type="circle" 
              :percentage="loadingProgress" 
              status="success">
            </el-progress>
            <el-progress 
              v-else-if="loadingStatus === 'exception'" 
              type="circle" 
              :percentage="loadingProgress" 
              status="exception">
            </el-progress>
            <el-progress 
              v-else 
              type="circle" 
              :percentage="loadingProgress">
            </el-progress>
          </div>
          <div v-if="pdfLoadError" class="pdf-overlay error">
            <div class="error-result">
              <i class="el-icon-error"></i>
              <h3>PDF加载失败</h3>
              <p>{{ errorMessage }}</p>
              <el-button type="primary" @click="retryLoading">重试</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ocrArtApi } from '@/api/ocrart'
// 导入vue-pdf-embed组件
import VuePdfEmbed from 'vue-pdf-embed'

export default {
  name: 'DocumentShow',
  components: {
    // 注册vue-pdf-embed组件
    VuePdfEmbed
  },
  data() {
    return {
      // 文档数据
      documentData: {
        wjbh: '', // 文件编号
        dh: '', // 档号
        bgqx: '', // 保管期限
        lbh: '', // 类别号
        ajh: '', // 案卷号
        jh: '', // 件号
        zrz: '', // 责任者
        ztsl: '', // 载体数量
        ztdw: '', // 载体单位
        ztgg: '', // 载体规格
        flh: '', // 分类号
        ztc: '', // 主题词
        fz: '', // 附注
        content: '', // 文档文本内容
        bt: '', // 题名
        fwjg: '', // 发文机关
        fwrq: '', // 发文日期
        mj: '', // 密级
        gjc: '', // 关键词
        wz: '', // 文种
        sj: '', // 时间
        wsh: '', // 微缩号
        dagh: '', // 档案管号
        sjlx: '', // 数据类型
        ztlx: '' // 载体类型
      },
      
      // PDF查看相关
      pdfViewMode: 'single', // 默认使用单层PDF
      pdfUrl: '', // 原始PDF文件URL
      pdfViewerUrl: '', // PDF.js viewer URL
      
      // 加载状态
      loading: false,
      loadingProgress: 0,
      loadingStatus: '',
      pdfLoadError: false,
      errorMessage: '',

      // 搜索相关
      searchText: '',
      currentPage: 1,
      totalPages: 0,
      matchCount: 0,
      currentMatchIndex: -1,
      searchMatches: [], // 存储搜索匹配项的位置信息
      pdfInstance: null,
      searchInitialized: false
    }
  },
  
  computed: {
    documentId() {
      return this.$route.query.id
    }
  },
  
  created() {
    // 添加全局消息监听
    window.addEventListener('message', this.handlePdfMessage);
    console.log('当前环境:', process.env.NODE_ENV);
    console.log('Base URL:', process.env.BASE_URL);
    this.fetchDocumentData();
  },
  
  mounted() {
    // 添加窗口大小变化监听
    window.addEventListener('resize', this.handleResize)
    console.log('组件已挂载，添加事件监听器');

    // 检查<embed>元素是否存在
    this.$nextTick(() => {
      if (this.$refs.pdfEmbed) {
        console.log('PDF嵌入元素存在');
      } else {
        console.error('PDF嵌入元素不存在');
      }
      setTimeout(() => {
        this.setupPdfListeners();
      }, 1000);
    });
  },
  
  beforeDestroy() {
    // 移除消息监听
    window.removeEventListener('message', this.handlePdfMessage);
    window.removeEventListener('resize', this.handleResize);
    
    console.log('组件将销毁，已清理资源');
  },
  
  watch: {
    pdfViewMode(newMode, oldMode) {
      // 如果模式发生变化，重新获取文档数据
      if (newMode !== oldMode && this.documentId) {
        console.log(`视图模式从 ${oldMode} 切换到 ${newMode}`);
        
        // 重新获取文档数据
        this.fetchDocumentData();

        // 如果切换到双层PDF模式，需要重新设置PDF监听
        if (newMode === 'double') {
          this.$nextTick(() => {
            this.setupPdfListeners();
          });
        }
      }
    }
  },
  
  methods: {
    // 获取文档数据
    async fetchDocumentData() {
      if (!this.documentId) return
      
      this.loading = true
      this.loadingStatus = ''
      this.loadingProgress = 30
      try {
        const response = await ocrArtApi('getDocById', { id: this.documentId })
        if (response.code === 200 && response.data) {
          console.log('获取文档数据成功:', response.data);
          this.documentData.dh = response.data.dh;
          this.documentData.tm = response.data.tm;
          this.documentData.ztc = response.data.ztc;
          this.documentData.mj = response.data.mj;
          this.documentData.bgqx = response.data.bgqx;
          this.documentData.flh = response.data.flh;
          this.documentData.ajh = response.data.ajh;
          this.documentData.jh = response.data.jh;
          this.documentData.gjc = response.data.gjc;
          this.documentData.lbh = response.data.lbh;
          this.documentData.wz = response.data.wz;
          this.documentData.sj = response.data.sj;
          this.documentData.wjbh = response.data.wjbh;
          this.documentData.ztlx = response.data.ztlx;
          this.documentData.ztsl = response.data.ztsl;
          this.documentData.ztdw = response.data.ztdw;  
          this.documentData.ztgg = response.data.ztgg;
          this.documentData.zrz = response.data.zrz;
          this.documentData.wsh = response.data.wsh;
          this.documentData.dagh = response.data.dagh;
          this.documentData.sjlx = response.data.sjlx;
          this.documentData.fz = response.data.fz;
          
          
          // 如果是文本模式，则无需加载PDF
          if (this.pdfViewMode === 'text') {
            console.log('文本模式，显示文本内容');
            // 如果API响应中没有content字段，可以尝试从其他字段获取
            if (!this.documentData.content && response.data.content) {
              this.documentData.content = response.data.content;
            }
            this.loading = false;
            return;
          }
          
          if (response.data.file_path || response.data.single_layer_pdf || response.data.double_layer_pdf) {
            let pdfUrl;
            if (this.pdfViewMode === 'single') {
              pdfUrl = response.data.single_layer_pdf || response.data.file_path;
            } else {
              pdfUrl = response.data.double_layer_pdf || response.data.file_path;
            }
            
            // 直接使用完整的PDF URL
            this.pdfUrl = pdfUrl;
            
            // 构建viewer URL
            if (this.pdfViewMode === 'double') {
              // 确保使用正确的viewer路径
              const viewerPath = '/static/pdfjs/web/viewer.html';
              this.pdfViewerUrl = `${viewerPath}?file=${encodeURIComponent(this.pdfUrl)}`;
              console.log('双层PDF URL:', this.pdfViewerUrl);
            } else {
              this.pdfViewerUrl = this.pdfUrl;
            }
            
            this.loadingProgress = 60;
          } else {
            throw new Error('文档路径不存在')
          }
          
          // 设置加载完成
          this.loadingProgress = 100;
          this.loadingStatus = 'success';
          this.loading = false;
          
        } else {
          throw new Error(response.message || '获取文档数据失败')
        }
      } catch (error) {
        console.error('获取文档数据出错:', error)
        this.pdfLoadError = true
        this.errorMessage = error.message || '获取文档数据失败'
        this.loadingStatus = 'exception'
        this.loading = false
      }
    },
    
    // 添加重试机制
    async retryLoadPdf(retryCount = 0) {
      if (retryCount >= 3) {
        this.pdfLoadError = true;
        this.errorMessage = '多次尝试加载PDF失败，请刷新页面重试';
        return;
      }

      console.log(`第${retryCount + 1}次尝试加载PDF`);
      try {
        await this.fetchDocumentData();
      } catch (error) {
        console.error('重试加载PDF失败:', error);
        setTimeout(() => {
          this.retryLoadPdf(retryCount + 1);
        }, 2000);
      }
    },
    
    // 修改现有的重试方法
    retryLoading() {
      this.pdfLoadError = false;
      this.loading = true;
      this.loadingProgress = 0;
      this.loadingStatus = '';
      this.retryLoadPdf();
    },
    
    // 处理窗口大小变化
    handleResize() {
      // 窗口大小变化时的处理逻辑
    },
    
    // 复制选中的文本
    copySelectedText() {
      try {
        // 使用浏览器自带的复制功能，无需特殊处理
        // embed 标签中的文本选择会自动被浏览器处理
        document.execCommand('copy');
        this.$message.success('文本已复制');
      } catch (error) {
        console.error('复制文本出错:', error);
        this.$message.error('复制失败: ' + error.message);
      }
    },
    
    // 处理双层PDF iframe加载完成事件，已不需要
    onDoublePdfIframeLoaded(event) {
      // 使用embed标签不再需要此方法
    },
    
    // 修正中文文本的阅读顺序，已不需要
    correctChineseTextOrder(text) {
      // 使用embed标签不再需要此方法
      return text;
    },
    
    // 测试文本反转，已不需要
    testTextReversal() {
      // 使用embed标签不再需要此方法
    },
    
    // 注入自定义样式到iframe中，只隐藏搜索相关的元素
    injectCustomStyles(event) {
      // 使用embed标签不再需要此方法
    },

    // 设置PDF监听器
    setupPdfListeners() {
      if (this.pdfViewMode === 'double' && this.$refs.pdfEmbed) {
        const embedElement = this.$refs.pdfEmbed;
        
        // 监听PDF加载完成
        embedElement.addEventListener('load', () => {
          console.log('PDF嵌入对象已加载');
          
          // 尝试获取PDF.js实例
          this.tryGetPdfInstance();
        });
      }
    },

    // 检查PDF.js是否正确加载
    checkPdfJsLoaded() {
      const iframe = this.$refs.pdfEmbed;
      if (iframe && iframe.contentWindow) {
        try {
          // 检查PDF.js的必要组件是否存在
          iframe.contentWindow.postMessage({
            type: 'CHECK_PDFJS_LOADED'
          }, '*');
          
          console.log('PDF.js检查消息已发送');
        } catch (error) {
          console.error('PDF.js检查失败:', error);
          this.pdfLoadError = true;
          this.errorMessage = 'PDF.js加载失败，请确保正确配置PDF.js';
        }
      }
    },

    // 修改 onPdfLoad 方法
    onPdfLoad(event) {
      console.log('PDF iframe loaded');
      try {
        const iframe = this.$refs.pdfEmbed;
        if (iframe) {
          console.log('PDF iframe element exists');
          
          // 延迟检查以确保PDF.js完全加载
          setTimeout(() => {
            this.checkPdfJsLoaded();
          }, 1000);
        }
      } catch (error) {
        console.error('PDF load error:', error);
        this.pdfLoadError = true;
        this.errorMessage = '加载PDF失败，请检查PDF文件是否可访问';
      }
    },

    // 尝试获取PDF.js实例
    tryGetPdfInstance() {
      try {
        console.log('尝试获取PDF.js实例...');
        const embedElement = this.$refs.pdfEmbed;
        if (!embedElement) {
          console.error('PDF嵌入元素不存在');
          return;
        }

        // 使用postMessage与iframe通信
        const checkPdfInstance = () => {
          try {
            // 发送消息给iframe
            embedElement.contentWindow.postMessage({
              type: 'GET_PDF_INSTANCE'
            }, '*');
            
            return true;
          } catch (err) {
            console.error('获取PDF.js实例失败:', err);
            return false;
          }
        };
        
        // 添加消息监听器
        window.addEventListener('message', (event) => {
          if (event.data && event.data.type === 'PDF_INSTANCE_READY') {
            console.log('PDF.js实例已就绪');
            this.pdfInstance = {
              findController: event.data.findController,
              eventBus: event.data.eventBus
            };
            this.$message.success('PDF加载完成，可以开始搜索');
          }
        });
        
        // 立即尝试一次
        if (!checkPdfInstance()) {
          let attempts = 0;
          const maxAttempts = 20;
          const interval = setInterval(() => {
            attempts++;
            console.log(`尝试获取PDF.js实例: 第 ${attempts} 次`);
            if (checkPdfInstance() || attempts >= maxAttempts) {
              clearInterval(interval);
              if (attempts >= maxAttempts && !this.pdfInstance) {
                console.error('无法获取PDF.js实例，已达到最大尝试次数');
                this.$message.error('PDF加载失败，请刷新页面重试');
              }
            }
          }, 500);
        }
      } catch (error) {
        console.error('设置PDF监听器出错:', error);
      }
    },

    // PDF加载完成事件
    onPdfLoaded() {
      this.loading = false;
      this.loadingProgress = 100;
      this.loadingStatus = 'success';
      
      // 获取PDF总页数
      if (this.$refs.pdfEmbed && this.$refs.pdfEmbed.pdf) {
        this.totalPages = this.$refs.pdfEmbed.pdf.numPages;
        console.log('PDF加载完成，总页数:', this.totalPages);
      }
    },
    
    // PDF渲染完成事件
    onPdfRendered() {
      console.log('PDF页面渲染完成');
      // 如果有搜索文本，执行搜索
      if (this.searchText) {
        this.searchInPdf();
      }
    },
    
    // 处理PDF加载错误
    handlePdfError(error) {
      console.error('PDF加载错误:', error);
      this.pdfLoadError = true;
      this.errorMessage = '加载PDF失败，请检查PDF文件是否可访问';
      this.loading = false;
    },
    
    // 在PDF中搜索文本
    async searchInPdf() {
      if (!this.searchText) {
        this.$message.warning('请输入搜索文本');
        return;
      }
      
      if (!this.$refs.pdfEmbed || !this.$refs.pdfEmbed.pdf) {
        this.$message.warning('PDF还未加载完成，请稍候再试');
        return;
      }
      
      try {
        console.log('开始搜索文本:', this.searchText);
        this.loading = true;
        
        // 清除之前的搜索结果
        this.searchMatches = [];
        this.currentMatchIndex = -1;
        
        const pdf = this.$refs.pdfEmbed.pdf;
        let totalMatches = 0;
        
        // 遍历所有页面进行搜索
        for (let pageNum = 1; pageNum <= pdf.numPages; pageNum++) {
          const page = await pdf.getPage(pageNum);
          const textContent = await page.getTextContent();
          
          const viewport = page.getViewport({ scale: 1 });
          const pageMatches = this.findTextInPage(textContent, this.searchText, viewport);
          
          if (pageMatches.length > 0) {
            this.searchMatches.push(...pageMatches.map(match => ({
              ...match,
              page: pageNum
            })));
            totalMatches += pageMatches.length;
          }
        }
        
        this.matchCount = totalMatches;
        
        if (this.matchCount === 0) {
          this.$message.info('未找到匹配文本');
        } else {
          this.$message.success(`找到 ${this.matchCount} 个匹配项`);
          // 导航到第一个匹配项
          this.navigateToMatch(0);
        }
        
        this.loading = false;
      } catch (error) {
        console.error('搜索PDF文本出错:', error);
        this.$message.error('搜索失败: ' + error.message);
        this.loading = false;
      }
    },
    
    // 在页面文本内容中查找匹配项
    findTextInPage(textContent, searchText, viewport) {
      const matches = [];
      const searchTextLower = searchText.toLowerCase();
      
      textContent.items.forEach(item => {
        const itemText = item.str.toLowerCase();
        let index = itemText.indexOf(searchTextLower);
        
        while (index !== -1) {
          const transform = viewport.transform;
          const [x, y] = this.adjustTextPosition(item, index, transform);
          
          matches.push({
            text: item.str.substr(index, searchTextLower.length),
            style: {
              left: `${x}px`,
              top: `${y}px`,
              width: `${item.width * (searchTextLower.length / item.str.length)}px`,
              height: `${item.height}px`
            }
          });
          
          index = itemText.indexOf(searchTextLower, index + 1);
        }
      });
      
      return matches;
    },
    
    // 调整文本位置
    adjustTextPosition(item, index, transform) {
      // 根据PDF.js的坐标系统计算实际位置
      const x = item.transform[4] + (index / item.str.length) * item.width;
      const y = item.transform[5] - item.height;
      
      return [x, y];
    },
    
    // 导航到指定匹配项
    navigateToMatch(index) {
      if (index < 0 || index >= this.searchMatches.length) {
        return;
      }
      
      this.currentMatchIndex = index;
      const match = this.searchMatches[index];
      
      // 如果匹配项在不同页面，先切换到该页面
      if (match.page !== this.currentPage) {
        this.currentPage = match.page;
      }
      
      // 滚动到匹配项位置
      setTimeout(() => {
        const matchElement = document.querySelector('.current-match');
        if (matchElement) {
          matchElement.scrollIntoView({
            behavior: 'smooth',
            block: 'center'
          });
        }
      }, 300);
    },
    
    // 导航到上一个或下一个匹配项
    navigateMatch(direction) {
      if (this.matchCount === 0) {
        this.$message.info('没有匹配项可导航');
        return;
      }
      
      let newIndex;
      if (direction === 'prev') {
        newIndex = this.currentMatchIndex > 0 ? this.currentMatchIndex - 1 : this.searchMatches.length - 1;
      } else {
        newIndex = this.currentMatchIndex < this.searchMatches.length - 1 ? this.currentMatchIndex + 1 : 0;
      }
      
      this.navigateToMatch(newIndex);
    },
    
    // 清除搜索结果
    clearSearch() {
      this.searchText = '';
      this.searchMatches = [];
      this.matchCount = 0;
      this.currentMatchIndex = -1;
      
      console.log('搜索结果已清除');
    },
    
    // 修改消息处理方法
    handlePdfMessage(event) {
      console.log('收到消息:', event.data);
      if (event.data && event.data.type) {
        switch (event.data.type) {
          case 'PDF_LOADED':
            console.log('PDF加载成功');
            this.loading = false;
            this.loadingStatus = 'success';
            break;
          case 'PDF_ERROR':
            console.error('PDF加载失败:', event.data.error);
            this.pdfLoadError = true;
            this.errorMessage = `加载PDF失败：${event.data.error || '未知错误'}`;
            break;
          case 'PDFJS_LOADED':
            console.log('PDF.js加载成功');
            break;
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
  height: calc(100vh - 84px);
  overflow: hidden;
}

.document-layout {
  display: flex;
  height: 100%;
  gap: 20px;
}

// 左侧元数据面板
.metadata-panel {
  width: 320px;
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.panel-header {
  padding: 15px;
  border-bottom: 1px solid #ebeef5;
  
  h2 {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    margin: 0;
  }
}

.metadata-scrollbar {
  flex: 1;
  height: 0;
}

.metadata-form {
  padding: 15px;
  
  ::v-deep .el-form-item {
    margin-bottom: 12px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    transition: all 0.3s ease;
    
    &:hover {
      border-color: #c0c4cc;
      box-shadow: 0 2px 6px rgba(0, 0, 0, 0.04);
    }
    
    .el-form-item__label {
      background-color: #f5f7fa;
      padding: 8px 12px;
      border-bottom: 1px solid #ebeef5;
      display: block;
      width: 100%;
      text-align: left;
      font-weight: 500;
      font-size: 13px;
      color: #606266;
      transition: background-color 0.3s ease;
    }
    
    .el-form-item__content {
      padding: 8px 12px;
      font-size: 13px;
      color: #606266;
      word-break: break-all;
      min-height: 36px;
      display: flex;
      align-items: center;
      
      &:empty::before {
        content: '-';
        color: #c0c4cc;
      }
    }
    
    &:hover .el-form-item__label {
      background-color: #eef1f6;
    }
  }
}

// 右侧PDF面板
.pdf-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.pdf-panel .panel-header {
  padding: 10px 15px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.left-controls {
  display: flex;
  align-items: center;
}

.zoom-controls {
  margin: 0 10px;
}

.page-info, .scale-info {
  min-width: 70px;
}

// PDF容器
.pdf-container {
  flex: 1;
  position: relative;
  overflow: hidden;
  background-color: #f5f5f5;
}

// PDF iframe容器
.pdf-iframe-container {
  width: 100%;
  height: 100%;
  position: relative;
  background: #404040;
  overflow: hidden;
}

.iframe-container {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
}

.pdf-iframe {
  width: 100%;
  height: 100%;
  border: none;
  display: block;
  background: transparent;
}

// 加载和错误状态
.pdf-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: rgba(255, 255, 255, 0.8);
  z-index: 100;
}

.pdf-placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.empty-placeholder {
  text-align: center;
  padding: 20px;
  i {
    font-size: 48px;
    color: #909399;
    margin-bottom: 10px;
  }
  p {
    font-size: 14px;
    color: #909399;
  }
}

.error-result {
  text-align: center;
  padding: 20px;
  i {
    font-size: 48px;
    color: #f56c6c;
    margin-bottom: 10px;
  }
  h3 {
    font-size: 16px;
    color: #606266;
    margin: 0;
  }
  p {
    font-size: 14px;
    color: #909399;
  }
}

/* 文本查看样式 */
.text-container {
  width: 100%;
  height: 100%;
  background-color: #f5f7fa;
  overflow: hidden;
}

.text-scrollbar {
  height: 100%;
  padding: 30px;
}

.document-paper {
  position: relative;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  padding: 40px;
  margin: 0 auto;
  max-width: 900px;
  min-height: calc(100% - 60px);
  color: #303133;
  font-size: 15px;
  line-height: 1.8;
  word-break: break-all;
  transition: all 0.3s ease;
  animation: fadeIn 0.5s ease-in-out;
  
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 6px;
    background: linear-gradient(to right, #4e7ccc, #3a8ee6, #67c23a);
    border-radius: 8px 8px 0 0;
  }
}

.document-title {
  text-align: center;
  font-size: 22px;
  font-weight: bold;
  margin-bottom: 30px;
  line-height: 1.5;
  color: #303133;
}

.document-metadata {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 25px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 6px;
  border-left: 4px solid #3a8ee6;
}

.metadata-item {
  margin-right: 20px;
  margin-bottom: 10px;
  font-size: 14px;
  
  .label {
    color: #606266;
    margin-right: 4px;
    font-weight: 500;
  }
  
  .value {
    color: #303133;
  }
}

.document-content {
  border-top: 1px dashed #dcdfe6;
  padding-top: 20px;
  
  pre {
    margin: 0;
    font-family: "Microsoft YaHei", Arial, sans-serif;
    white-space: pre-wrap;
    font-size: 15px;
    line-height: 1.8;
  }
}

.empty-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 0;
  
  i {
    font-size: 60px;
    color: #dcdfe6;
    margin-bottom: 20px;
  }
  
  p {
    font-size: 16px;
    color: #909399;
    margin-bottom: 20px;
  }
}

.loading-placeholder {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  padding: 40px;
  margin: 0 auto;
  max-width: 900px;
  min-height: calc(100% - 60px);
}

// 响应式样式
@media (max-width: 1200px) {
  .document-layout {
    flex-direction: column;
  }
  
  .metadata-panel {
    width: 100%;
    height: 30%;
    min-height: 200px;
  }
  
  .pdf-panel {
    height: 70%;
  }
}

/* 在单层PDF模式下隐藏工具栏和搜索相关元素 */
.single .pdf-iframe {
  :deep(#toolbarContainer),
  :deep(#findbar),
  :deep(#secondaryToolbar),
  :deep(.findbar),
  :deep(.toolbar),
  :deep(.toolbarButton),
  :deep(#toolbarViewFind),
  :deep(#findbarOptionsOneContainer),
  :deep(#findbarOptionsTwoContainer),
  :deep(#findInputAutoComplete),
  :deep(#findMsg),
  :deep(button[data-l10n-id="find_previous"]),
  :deep(button[data-l10n-id="find_next"]),
  :deep(.findbar .toolbarField),
  :deep(.textLayer) {
    display: none !important;
    pointer-events: none !important;
    visibility: hidden !important;
  }
}

/* 确保iframe内容可以全屏显示 */
.pdf-iframe {
  width: 100%;
  height: 100%;
  border: none;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 不再需要的样式 */
.vue-pdf-container,
.vue-pdf,
.pdf-controls {
  display: none;
}

.pdf-loading {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 20;
}

.el-loading-spinner {
  text-align: center;
  
  i.el-icon-loading {
    font-size: 32px;
    color: #409EFF;
  }
  
  .el-loading-text {
    margin-top: 10px;
    font-size: 14px;
    color: #606266;
  }
}

.test-toolbar {
  position: absolute;
  top: 10px;
  right: 10px;
  z-index: 30;
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 4px;
  padding: 5px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pdf-embed {
  width: 100%;
  height: 100%;
  border: none;
  background-color: #f5f7fa;
}

// 搜索控件样式
.search-controls {
  display: flex;
  align-items: center;
  gap: 5px;
  margin-left: 16px;
}

.search-input {
  width: 200px;
}

.nav-button {
  padding: 7px;
}

.match-info {
  font-size: 12px;
  color: #606266;
  margin-left: 5px;
  min-width: 40px;
  text-align: center;
}

.clear-button {
  margin-left: 5px;
}

/* 双层PDF模式下允许搜索相关元素显示 */
.double .pdf-iframe {
  :deep(#toolbarContainer),
  :deep(#findbar),
  :deep(#secondaryToolbar) {
    display: block !important;
    visibility: visible !important;
    pointer-events: auto !important;
  }
}

// 添加新样式
.pdf-embed-container {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: auto;
}

.search-highlights-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
}

.search-highlight {
  position: absolute;
  background-color: rgba(255, 255, 0, 0.3);
  border-radius: 2px;
  pointer-events: auto;
  cursor: pointer;
}

.current-match {
  background-color: rgba(255, 165, 0, 0.5);
  z-index: 2;
}
</style>
